const numeral = require("../../../vendor/numeral/numeral.min")
const regeneratorRuntime = require('../../../vendor/regenerator-runtime')
const co = require('../../../vendor/co')
const parser = require('../../../vendor/wxParse/wxParse')
const config = require('../../../config')
const app = getApp()
const TYPE_TG = 'tg'
let tid = 0

//根据秒数计算时分秒
function computeTime(val) {
    if (val < 0) {
        return "00时00分00秒"
    }
    function format(d) {
        return d < 10 ? ("0" + d) : d
    }
    var h = parseInt(val / 3600)//时
    var _h = val - h * 3600//除去 小时 剩余的秒数
    var m = parseInt(_h / 60)//分
    var s = _h % 60//秒
    return format(h) + "时" + format(m) + "分" + format(s) + "秒"
}

Page({
    data: { num: 1, selected_tg: 0, status: 1 },
    onLoad(options) {
        options.width = app.window.width
        options.mid = wx.getStorageSync("mid")
        this.setData(options)
        this.getGoodsInfo()


    },
    onShow() {
        this.hideDetail()
    },
    /**
     * 获取商品信息
     */
    getGoodsInfo() {
        wx.showLoading({
            title: '加载中...',
        })
        this.setData({
            loading: true
        })
        app.http.get("goods/detail", {
            data: { id: this.data.id },
        }).then(result => {
            wx.setNavigationBarTitle({ title: result.data.info.name })
            result.data.comment.forEach(o => {
                o.star = +o.star
            })
            result.data.group_list.forEach(o => {
                o.left_num = o.need_number - o.children.length - 1
            })
            if (result.data.group_team.length > 0) {
                const g = result.data.group_team[0]
                this.setData({
                    saveMoney: g.num + "人团省" + (result.data.info.mall_price - g.price).toFixed(2) + "元"
                })
            }

            let isShowGroup = true
            if (result.data.lucky) {
                isShowGroup = result.data.info.is_show_group ? true : false
            }

            let isTgFree = result.data.group_team.find(o => o.is_free) ? 1 : 0
            // result.data.selectedSpec = result.data.spec.map(o => -1)
            wx.hideLoading()
            this.setData(Object.assign({ loading: false, isTgFree, isShowGroup }, result.data))
            if (result.data.detail) {
                parser.wxParse("detail", "html", result.data.detail.content, this)
            }
            this.startTimer()
        }).catch(err => {
            app.wxToast.error(err.message)
        })
    },
    update() {
        this.setData(data)
    },
    startTimer() {
        var team = this.data.group_list
        var f = function () {
            var current = parseInt(new Date().getTime() / 1000)
            team.forEach(function (o) {
                o.clock = computeTime(parseInt(o.end_time) - current)
            })
            this.setData({
                group_list: team
            })
        }.bind(this)
        if (team.length) {
            clearInterval(tid)
            tid = setInterval(function () {
                f()
            }, 1000)
        }
        f()
    },

    computePrice() {
        let p = +this.data.info.mall_price
        if (this.data.buyType == 2) {
            p = +this.data.group_team[this.data.selected_tg].price
        }
        let sku = this.data.selectedSku
        let p2 = p
        if (sku) {
            p2 += sku.price / 100
        }
        p2 = Math.max(0.01, p2)
        this.setData({
            baseDetailPrice: p,
            detailPrice: numeral(p2).format('0,0.00')
        })
    },

    clickTg(evt) {
        const { index } = evt.currentTarget.dataset
        this.setData({
            selected_tg: index,
        })
        this.computePrice()
    },

    showDetail(evt) {
        let buyType = evt.currentTarget.dataset.type
        this.setData({
            buyType
        })
        this.computePrice()
        if (this.data.spec.length > 0) {
            this.setData({
                spec: this.data.spec.map(o => {
                    o.selected = -1
                    return o
                }),
                isDetailShow: true,
                selectedSku: false,
            })
            return
        }
        if (buyType == 1) {
            wx.navigateTo({
                url: '../../pay/pay?id=' + this.data.info.id,
            })
        } else {
            if (this.data.group_team.length > 1) {
                this.setData({
                    isDetailShow: true,
                })
            } else {
                wx.navigateTo({
                    url: '../../pay/pay?id=' + this.data.info.id + "&tid=" + this.data.group_team[0].id,
                })
            }
        }

    },

    clickSpec(evt) {
        const { row, col } = evt.currentTarget.dataset
        this.setData({
            [`spec[${row}].selected`]: col
        })
        let skuName = this.data.spec.map(o => {
            return o.child[o.selected] ? o.child[o.selected].name : "--"
        }).join("#")
        this.setData({
            selectedSku: this.data.sku.find(o => o.name == skuName),
        })
        this.computePrice()
    },
    hideDetail() {
        this.setData({
            isDetailShow: false,
        })
    },

    buy() {
        let data = this.data
        const ps = ["id=" + this.data.id]
        var sel = this.data.spec.filter(function (o) {
            return !o.child[o.selected]
        })
        if (sel.length) {
            app.wxToast.warn('请选择 ' + sel[0].name)
            return
        }
        if (this.data.selectedSku && this.data.selectedSku.stock <= 0) {
            return
        }


        if (this.data.buyType == 2) {
            ps.push("tid=" + this.data.group_team[this.data.selected_tg].id)
        }
        this.data.selectedSku && ps.push("sku_id=" + this.data.selectedSku.id)
        wx.navigateTo({
            url: '../../pay/pay?' + ps.join("&"),
        })
    },


    //收藏商品
    keep(evt) {
        this.setData({
            is_keep: !this.data.is_keep
        })
        app.http.get("goods/collect", {
            data: { id: this.data.info.id }
        }).then(res => {

        }).catch(err => {
            app.wxToast.error('操作失败')
        })
    },
    /**
     * 数量+
     */
    plus() {
        let data = this.data
        let d = data.num + 1
        this.setData({ num: d })
    },
    /**
     * 数量-
     */
    minus() {
        let d = data.num - 1
        if (d <= 1) d = 1
        this.setData({ num: d })
    },

    num_input(evt) {
        var val = parseInt(evt.detail.value)
        if (isNaN(val)) {
            val = 1
        }
        if (val == 0) {
            val = 1
        }
        this.setData({
            num: val
        })

        return val
    },
    /**
     * 分享
     */
    onShareAppMessage() {
        console.log(app.getShareObj(this.data.goods.name, {
            id: this.data.goods.id
        }), 'xxxxxxxxxx')


        return app.getShareObj(this.data.goods.name, {
            id: this.data.goods.id
        })
    },


    switchDetail(evt) {
        this.setData({ status: evt.currentTarget.dataset.status })
    },


    viewComment(evt) {
        let data = this.data
        // app.global_data.commentGoodsInfo = {
        //     id: data.goods.id,
        //     cover: data.goods.images[0],
        //     title: data.goods.name
        // }
        wx.navigateTo({ url: `./comment?id=${this.data.info.id}` })
    },

    stop() { },

    onPageScroll(e) {
        let top = e.scrollTop
        this.setData({
            top
        })
    },
    onPullDownRefresh() {
        this.setData({
            group_list: [],
            group_team: [],
        })
        this.getGoodsInfo()
    },
    goLucky() {
        const ps = getCurrentPages()
        if (ps.length > 2) {
            const route = ps[ps.length - 2].route
            if (route == "pages/goods/lucky") {
                wx.navigateBack({

                })
            }
        } else {
            wx.navigateTo({
                url: "/pages/goods/lucky?id=" + this.data.lucky.id,
            })
        }


    }
})
